const app = getApp();
var md5 = require("../../utils/md5.js");
var util = require('../../utils/util.js')
import Toast from '../../assets/vant/toast/toast';
var amapFile = require('../../utils/amap-wx.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        hasLogin: false,
        permission: false,
        openid: null,
        phoneNumber: null,
        session_key: null,

        marginTop: null,
        popshow: false, //弹窗
        libraryList: [], //图书馆列表
        currentLibraryIndex: 0,
        currentLibraryId: null,
        isOver: true,
        currentSite: null,

        province: '',
        city: '',
        district: '',
        latitude: '',
        longitude: '',

        pageNumber: 1,
        listType: 'local',
        allowLocation: true,
        hasRelaunch: false,
        sw: "",
        //作品详情定制参数
        activityId: "",
        type: "",
        fid: "",
        canIUseGetUserProfile:false,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        //屏蔽右上角分享功能
        wx.hideShareMenu();
        console.log(options);
        if (JSON.stringify(options) != "{}") {
            console.log("参数");
            var activityId = options.activityId;
            var type = options.type;
            var fid = options.fid;
            this.setData({
                activityId: activityId,
                type: type,
                fid: fid
            })
        }

        var hasLogin = wx.getStorageSync('hasLogin');
        var permission = wx.getStorageSync('permission');
        this.setData({
            hasLogin: hasLogin == undefined ? false : hasLogin,
            permission: permission == undefined ? false : permission,
            // allowLocation: app.globalData.allowLocation
        })
        if (wx.getUserProfile) {
            this.setData({
              canIUseGetUserProfile: true
            })
          }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function(options) {

    },

    /**
     * 授权获取用户头像信息
     */
    bindGetUserInfo: function(e) {
        console.log(e);
        if (e.detail.errMsg == "getUserInfo:fail auth deny") {

        } else if (e.detail.errMsg == "getUserInfo:ok") {
            this.setData({
                hasLogin: true
            })
            wx.setStorageSync('userInfo', e.detail.userInfo)
            wx.setStorageSync('hasLogin', true);
        }

    },

      //新版获取用户信息
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        wx.setStorageSync('userInfo', res.userInfo)
        wx.setStorageSync('hasLogin', true);
        this.setData({
          hasLogin: true
        })
      }
    })
  },
   
    /**
     * 获取用户手机号
     */
    getPhoneNumber: function(e) {
        var that = this;
        //主动获取code
        // var code = '';
        wx.login({
            success: res => {
                if (res.errMsg == 'login:ok') {
                    // code = res.code;
                    wx.setStorageSync('code', res.code);
                }
            }
        })
        var code = wx.getStorageSync("code");
        console.log("登录： " + code);
        if (e.detail.errMsg == "getPhoneNumber:fail user deny") {
            console.log("拒绝授权手机号")
        } else if (e.detail.errMsg == "getPhoneNumber:ok") {
            console.log("开始授权")
            var encarr = [{
                js_code: code
                }, {
                    grant_type: 'authorization_code'
                }, {
                    fid: app.globalData.fid
                }, {
                    from: 'cx'
                }, {
                    defaultFid: '132334'
                }]
              var enc = app.generateEnc(encarr)
            wx.request({
                url: 'https://wxgt.chaoxing.com/wechat/getSessionAndOpenid',
                data: {
                    js_code: code,
                    grant_type: 'authorization_code',
                    fid: app.globalData.fid,
                    from: 'cx',
                    defaultFid: '132334',
                    enc: enc
                },
                success: function(res) {
                    if (res.data.code == 200) {
                        that.setData({
                            openid: res.data.data.openid,
                            session_key: res.data.data.session_key
                        })
                        wx.setStorageSync('openid', res.data.data.openid);
                        wx.setStorageSync('session_key', res.data.data.session_key);
                        that.getPhoneNumberBySupporter(e.detail.encryptedData, e.detail.iv)
                    } else {
                        console.log("code已失效");
                        wx.login({
                            success: res => {
                                if (res.errMsg == 'login:ok') {
                                    wx.setStorageSync('code', res.code);
                                }
                            }
                        })
                    }

                },
                fail: function() {
                    console.log("获取session失败")
                }
            })
        }

    },

    /**
     * 查询手机号业务
     */
    getPhoneNumberBySupporter: function(enc, iv) {
        var that = this;
        var encarr = [{
            appId: app.globalData.appId
            }, {
                sessionKey: that.data.session_key
            }, {
                encryptedData: enc
            }, {
                iv: iv
            }, {
                fid: app.globalData.fid
            }]
        var newenc = app.generateEnc(encarr)
        wx.request({
            url: 'https://wxgt.chaoxing.com/wechat/getPhoneNumber?fid=' + app.globalData.fid + '&appId=' + app.globalData.appId + '&sessionKey=' + encodeURIComponent(that.data.session_key) + '&encryptedData=' + encodeURIComponent(enc) + '&iv=' + encodeURIComponent(iv) + '&enc=' + newenc,
            success: function(res) {
                if (res.data.code == 200) {
                    that.setData({
                        phoneNumber: res.data.data.phoneNumber
                    })
                    wx.setStorageSync('phone', res.data.data.phoneNumber)
                    that.checkUserInfoByPhoneNumber(res.data.data.phoneNumber,enc, iv);
                }
            },
            fail: function() {
                console.log("获取用户手机号失败");
            }
        })
    },

    /**
     * 根据手机号去查询用户是否存在于超星
     */
    checkUserInfoByPhoneNumber: function(phoneNumber,enc, iv) {
        var that = this;
        var userinfo = wx.getStorageSync('userInfo');
        var nickName = "";
        if (userinfo != undefined) {
            nickName = encodeURIComponent(userinfo.nickName);
        }
        var encarr = [{
            uname: phoneNumber
            }, {
                schoolid: app.globalData.fid
            }, {
                realName: nickName
            }]
          var enc = app.generateEnc(encarr)
        wx.request({
            url: 'https://wxgt.chaoxing.com/wechat/checkUserByPhone',
            method: 'get',
            data: {
                uname: phoneNumber,
                realName: nickName,
                schoolid: app.globalData.fid,
                enc: enc
            },
            success: function(res) {
                if (res.data.code == 200) {
                    if(res.data.data.result == true){
                        //存在当前用户
                    that.setData({
                        // openid4: res.data.data.openid4,
                        dxfid: res.data.data.dxfid,
                        cxid: res.data.data.uid,
                        realname: res.data.data.realname,
                        permission: true
                    })
                    wx.setStorageSync("cxid", res.data.data.uid);
                    wx.setStorageSync('realname', res.data.data.realname);
                    // wx.setStorageSync("openid4", res.data.data.openid4);
                    wx.setStorageSync('permission', true);
                    that.getSessionKey(enc, iv)
                    // that.audioGuideLogin(enc, iv)
                    that.goback();
                    }else{
                        that.getRealnameByPhoneNumber(phoneNumber,enc, iv);
                    }    
                } 
            },
            fail: function() {
                console.log("获取用户信息失败");
            }
        })
    },

    /**
   * 根据手机号去查询用户是否存在于超星(查询realname)
   */
  getRealnameByPhoneNumber: function (phoneNumber,enc, iv) {
    var that = this;
    var encarr = [{
        uname: phoneNumber
        }, {
          schoolid: app.globalData.fid
        }]
      var enc = app.generateEnc(encarr)
    wx.request({
      url: 'https://wxgt.chaoxing.com/mooc/getUserByPhone',
      method: 'get',
      data: {
        uname: phoneNumber,
        schoolid: app.globalData.fid,
        enc: enc
      },
      success: function (res) {
        if (res.data.code == 200) {
          //存在当前用户 realname加入缓存
          that.setData({
            // openid4: res.data.data.openid4,
                dxfid: res.data.data.dxfid,
                cxid: res.data.data.uid,
                realname: res.data.data.realname,
                permission: true
            })
            wx.setStorageSync("cxid", res.data.data.uid);
            wx.setStorageSync('realname', res.data.data.realname);
            wx.setStorageSync('permission', true);
            that.getSessionKey(enc, iv)
            that.goback();
            } else {
            console.error("查询用户信息出错或者用户不存在");
            }
      },
      fail: function () {
        console.error("获取用户信息失败");
      }
    })
  },

  audioGuideLogin:function(enc, iv){
      let that=this
    wx.request({
        url: app.globalData.baseUrl + 'auth/jwt/wechat-token',
        data: {
          "encryptedData": encodeURI(enc),
          "iv": encodeURI(iv),
          "openId":wx.getStorageSync('openId')
        },
        header: {
          'content-type': 'application/json',
          // 'Cookie': wx.getStorageSync('cookieKey')
          'Authorization': wx.getStorageSync('cookieKey')
        },
        success(res) {
          console.log(22222,res)
          if (res.data.data != '获取失败！') {
            wx.setStorageSync('token', res.data.data); //保存token到Storage
            wx.showToast({
              title: '登录成功',
              icon: 'success',
              duration: 1000
            })
          } else {
            wx.showToast({
              title: '登录失败，请退出重试哦',
              icon: 'none',
              duration: 1000
            })
          }
        }
      })
  },
  getSessionKey(enc, iv){
      let that=this
    let code=wx.getStorageSync('code');
    wx.request({
        url: app.globalData.baseUrl + 'auth/jwt/session-key?code=' +  code+'&museumCode='+app.globalData.museumCode,
        header: {
          'content-type': 'application/json'
        },
        success(res) {
            if (res && res.header && res.header['Set-Cookie']) {
                console.log('保存cookie',res)
                wx.setStorageSync('cookieKey', res.header['Set-Cookie']); //保存Cookie到Storage
            }
            if(res.data.rel){
                wx.setStorageSync('openId', res.data.data)
                that.audioGuideLogin(enc, iv)
            }
        }
      })
    
  },
  
    /**
     * 注册学习通用户
     */
    registerUser: function(fid, phone) {
        var that = this;
        var encarr = [{
            fid: fid
        }, {
            phone: phone
        }]
        var enc = app.generateEnc(encarr)
        wx.request({
            url: 'https://wxgt.chaoxing.com/wechat/registerUser',
            method: 'post',
            data: {
                fid: fid,
                phone: phone,
                enc:enc
            },
            success: function(res) {

                if (res.data.code == 200) {
                    //存在当前用户
                    that.setData({
                        cxid: res.data.data.uid,
                        permission: true
                    })
                    wx.setStorageSync("cxid", res.data.data.uid);
                    wx.setStorageSync('permission', true);
                    that.goback();
                } else if (res.data.code == 202) {
                    //不存在当前用户，需要注册用户
                    console.log("注册失败");
                }
            },
            fail: function() {
                console.log("注册用户信息失败");
            }
        })

    },

    goback: function() {
        if (!this.data.hasRelaunch) {
            if (this.data.activityId != "" && this.data.activityId != undefined) {
                console.log("自定义跳转");
                var uid = wx.getStorageSync('cxid') == undefined ? "" : wx.getStorageSync('cxid');
                wx.redirectTo({
                    url: decodeURIComponent("/pages/link/link?url=https://videoshequ3.chaoxing.com/miniprogram/play&activityId=" + this.data.activityId + "&type=" + this.data.type + "&uid=" + uid + "&fid=" + this.data.fid),
                })
            } else {
                console.log("通用跳转");
                wx.navigateBack({
                  delta: 1,
                })
                // wx.navigateBack({

                // })
            }
        } else {
            wx.reLaunch({
                url: '/pages/index/index'
            })
        }
    },

    /**
     * 图书馆确定按钮
     */
    bindsure: function() {
        this.setData({
                popshow: false,
                currentLibraryId: null,
                allowLocation: true,
                hasRelaunch: true
            })
            //TODO 需要将对应图书馆的信息写入app.js 然后加载页面
        let site = this.data.currentSite;
        app.globalData.site = site;
        app.globalData.fid = site.fid;
        app.globalData.fidEnc = site.fidEnc;
        app.globalData.province = site.province;
        app.globalData.city = site.city;
        app.globalData.district = site.district;
        app.globalData.allowLocation = true;
        wx.setStorageSync("fid", site.fid);
        this.getMuseumCode(site.fid)
    },
    //根据fid获取museumCode
  getMuseumCode(fid){
    wx.request({
        url: app.globalData.baseUrl +'admin/front/group/code',
        method: 'get',
        data: {
            fid: fid
        },
        success: function(res) {
            console.log(222222,res)
            if (res.statusCode == 200) {
                 let data=res.data
                 if(data && data.status==200){
                   app.globalData.museumCode=data.data;
                 }else{
                  console.log("获取museumCode失败");
                 }
            } else {
                console.log("获取museumCode失败");
            }
        },
        fail: function() {
            console.log("获取museumCode失败");
        }
    })
},
    /**
     * 关闭弹窗
     */
    closeWrapper: function() {
        this.setData({
            popshow: false
        })
    },
    /**
     * 图书馆列表分页
     * 
     */
    addrscrolltolower: function() {
        if (this.data.listType == "local") {
            this.getCities()
        } else {
            this.searchLibrary(this.data.sw)
        }
    },
    /**
     * 重新定位
     */
    refreshAddr: function() {
        this.setData({
            currentLibraryId: null,
            pageNumber: 1,
            libraryList: [],
            listType: 'local'
        })
        this.getUserLocation();
    },
    /**
     * 选择图书馆
     */
    checkCurrentLibrary: function(e) {
        var currentId = e.currentTarget.dataset.id;
        this.setData({
            currentSite: this.data.libraryList[currentId]
        })

    },
    inputEventListener: function(e) {
        this.setData({
            sw: e.detail
        })
    },
    onClickIcon: function(e) {
        console.log(e)
        this.setData({
            libraryList: [],
            pageNumber: 1,
            listType: 'search'
        })
        let sw = this.data.sw.value;
        if (sw != "" && sw != undefined) {
            this.searchSites(sw)
        }
    },
    onSearchLibrary: function(e) {
        let vm = this;
        vm.setData({
            listType: 'search',
            sw: e.detail,
            libraryList: [],
            pageNumber: 1
        })
        vm.searchSites(vm.data.sw)
    },

    searchLibrary: function(sw) {
        let vm = this;
        vm.setData({
            listType: 'search',
            sw: sw,
            pageNumber: 1
        })
        vm.searchSites(sw)
    },

    /**
     * 搜索站点
     */
    searchSites: function(name) {
        let vm = this;
        var encarr = []
    if (name == '') {
      encarr = [{
        pageSize: 10
      }, {
        pageNumber: vm.data.pageNumber
      }, {
        order: 1
      }, {
        libraryType: 3
      }]
    } else {
      encarr = [{
        pageSize: 10
      }, {
        pageNumber: vm.data.pageNumber
      }, {
        sw: name
      }, {
        order: 1
      }, {
        libraryType: 3
      }]
    }
    var enc = app.generateEnc(encarr)
        wx.request({
            url: 'https://manageshequ3.chaoxing.com/api/searchsite',
            data: {
                sw: name,
                pageSize: 6,
                pageNumber: vm.data.pageNumber,
                order: 1,
                libraryType: 3,
                enc:enc
            },
            success: function(res) {
                console.log(res)
                if (res.data.code == 200) {
                    if (res.data.data.total == 0) {
                        let site = {
                            fid: 132334,
                            id: 2932,
                            fidEnc: 'e86afc8a7b52e909',
                            name: '博以览物',
                            custom: '{"AccessID": "","key": ""}'
                        }
                        res.data.data.records[res.data.data.records.length] = site
                    }
                    var records = res.data.data.records
                    records.forEach(t => {
                      try {
                        JSON.parse(t.custom)
                      } catch (error) {
                        t.custom = t.custom!='' ? app.decrypt(t.custom) : t.custom
                        t.appid = t.appid!='' ? app.decrypt(t.appid) : t.appid
                        t.fidEnc = t.fidEnc!='' ? app.decrypt(t.fidEnc) : t.fidEnc
                        t.fidEncH5 = t.fidEncH5!='' ? app.decrypt(t.fidEncH5) : t.fidEncH5
                        t.secret = t.secret!='' ? app.decrypt(t.secret) : t.secret
                      }
                    })
                    vm.setData({
                        libraryList: vm.data.libraryList.concat(records),
                        pageNumber: vm.data.pageNumber + 1
                    })
                }
            },
            fail: function() {
                console.log("获取当前城市下属单位失败")
            }
        })
    },

    getUserLocation: function(e) {
        var vm = this;
        wx.getSetting({
            success: (res) => {
                if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
                    wx.showModal({
                        title: '请求授权当前位置',
                        content: '需要获取您的地理位置，请确认授权',
                        success: function(res) {
                            if (res.cancel) {
                                wx.showToast({
                                    title: '拒绝授权',
                                    icon: 'none',
                                    duration: 1000
                                })
                                console.log("拒绝授权地理位置 展示默认列表")

                                //TODO 拒绝授权地理位置，使用默认的app.js数据加载首页资源
                            } else if (res.confirm) {
                                wx.openSetting({
                                    success: function(dataAu) {
                                        if (dataAu.authSetting["scope.userLocation"] == true) {
                                            wx.showToast({
                                                    title: '授权成功',
                                                    icon: 'success',
                                                    duration: 1000
                                                })
                                                //再次授权，调用wx.getLocation的API
                                            vm.getLocation();
                                        } else {
                                            wx.showToast({
                                                title: '授权失败',
                                                icon: 'none',
                                                duration: 1000
                                            })
                                        }
                                    }
                                })
                            }
                        }
                    })
                } else if (res.authSetting['scope.userLocation'] == undefined) {
                    //调用wx.getLocation的API
                    vm.getLocation();
                } else {
                    //调用wx.getLocation的API
                    vm.getLocation();
                }
            }
        })
    },
    // 微信获得经纬度
    getLocation: function() {
        let vm = this;
        wx.getLocation({
            type: 'wgs84',
            success: function(res) {
                var latitude = res.latitude
                var longitude = res.longitude
                var speed = res.speed
                var accuracy = res.accuracy;
                vm.loadCity(latitude, longitude)
            },
            fail: function(res) {
                console.log('fail' + JSON.stringify(res))
                wx.getSetting({
                    success: function(res) {
                        if (!res.authSetting['scope.userLocation']) {
                            console.log("用户拒绝授权")
                        } else {
                            //用户已授权，但是获取地理位置失败，提示用户去系统设置中打开定位
                            wx.showModal({
                                title: '',
                                content: '请在系统设置中打开定位服务',
                                confirmText: '确定',
                                success: function(res) {}
                            })
                        }
                    }
                })
            }
        })
    },

    //获取当前城市所属单位
    getCities: function() {
        let vm = this;
        var encarr = [{
            pageSize: 6
          }, {
            pageNumber: this.data.pageNumber
          }, {
            city: this.data.city
          }, {
            libraryType: 3
          }]
          var enc = app.generateEnc(encarr)
        wx.request({
            url: 'https://manageshequ3.chaoxing.com/api/citysites',
            data: {
                city: this.data.city,
                pageSize: 6,
                pageNumber: this.data.pageNumber,
                libraryType: 3, //类型 1图书馆 add by carlos at 2020-05-20
                sid: 1, //预留字段 add by carlos at 2020-05-20
                enc:enc
            },
            success: function(res) {
                console.log(res)
                if (res.data.code == 200) {
                    if (res.data.data.total == 0) {
                        let site = {
                            fid: 117890,
                            id: 1,
                            fidEnc: 'd6517f679046dcf3',
                            name: '超星读书',
                            custom: '{"AccessID": "","key": ""}'
                        }
                        res.data.data.records[res.data.data.records.length] = site
                    }
                    var records = res.data.data.records
                    records.forEach(t => {
                      try {
                        JSON.parse(t.custom)
                      } catch (error) {
                        t.custom = t.custom!='' ? app.decrypt(t.custom) : t.custom
                        t.appid = t.appid!='' ? app.decrypt(t.appid) : t.appid
                        t.fidEnc = t.fidEnc!='' ? app.decrypt(t.fidEnc) : t.fidEnc
                        t.fidEncH5 = t.fidEncH5!='' ? app.decrypt(t.fidEncH5) : t.fidEncH5
                        t.secret = t.secret!='' ? app.decrypt(t.secret) : t.secret
                      }
                    })
                    vm.setData({
                        libraryList: vm.data.libraryList.concat(records),
                        pageNumber: vm.data.pageNumber + 1
                    })
                }
            },
            fail: function() {
                console.log("获取当前城市下属单位失败")
            }
        })
    },

    //把当前位置的经纬度传给高德地图，调用高德API获取当前地理位置，天气情况等信息
    loadCity: function(latitude, longitude) {
        var vm = this;
        var myAmapFun = new amapFile.AMapWX({ key: 'fe45065f41c8ace6763bd2ca631ddad7' });
        myAmapFun.getRegeo({
            location: '' + longitude + ',' + latitude + '', //location的格式为'经度,纬度'
            success: function(res) {
                let address = res[0].regeocodeData.addressComponent;
                let province = address.province;
                let district = address.district;
                let city = address.city;
                if (city.length == 0) {
                    city = province
                }
                app.globalData.province = province;
                app.globalData.city = city;
                app.globalData.district = district;
                vm.setData({
                    province: province,
                    city: city,
                    district: district,
                    popshow: true
                })
                vm.getCities();
            },
            fail: function(info) {

            }
        });
    }
})